package com.ticket.sass.common.ticketserver.platform.fhyz

import okhttp3.*
import okio.Buffer
import org.slf4j.LoggerFactory
import java.nio.charset.Charset
import java.time.Duration
import java.time.LocalDateTime

object RequestClient {
    private val logger = LoggerFactory.getLogger(RequestClient::class.java)

    private val okHttpClient = OkHttpClient.Builder()
        .addInterceptor(Interceptor { chain ->
            val request = chain.request()

            val requestBody = request.body?.let {
                val requestBodyBuffer = Buffer()
                it.writeTo(requestBodyBuffer)
                requestBodyBuffer.readString(Charset.forName("UTF-8"))
            }

            val beginTime = LocalDateTime.now()
            val response = chain.proceed(request)

            val responseBody = response.body?.let {
                it.source().request(Long.MAX_VALUE)
                it.source().buffer.clone().readString(Charset.forName("UTF-8"))
            }

            val endTime = LocalDateTime.now()
            val between = Duration.between(beginTime, endTime)
            val millis = between.toMillis()

            logger.info("请求时间：${millis}毫秒, 请求地址：${request.url}，请求参数：${requestBody}，响应状态码：${response.code}，响应数据：${responseBody}")

            response
        })
        .build()

    /**
     * 发送请求
     *
     * @param params 请求参数
     * @param sign 签名
     * @param env 使用环境
     */
    fun send(params: List<Map<String, Any?>>, sign: String, env: Configurer.Env? = null): String {

        val requestBody = FormBody.Builder().let { bodyBuilder ->
            params.forEach {
                bodyBuilder.add(it.keys.first(), it.values.first().toString())
            }
            bodyBuilder.add("sign", sign)
            bodyBuilder.build()
        }

        val request = Request.Builder()
            .url(env?.url ?: Configurer.Env.ONLINE.url)
            .post(requestBody)
            .build()

        val response = okHttpClient.newCall(request).execute()

        return response.body?.string() ?: error("接口无数据响应")
    }
}